<?php

namespace App\store\controllers;

use App\store\controllers\StoreBaseController;
use App\common\models\ThreeLogin;
use App\store\models\Members;
use App\store\models\MembersLoginLogs;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;

class LogonController extends StoreBaseController
{

    /**
     * 获取用户手机号
     */
    public function getUserPhone(Request $request)
    {

        $tmp = self::getAccessToken();
        $tmptoken = json_decode($tmp);
        $token = $tmptoken->access_token;
        $data = $request->only('code');

        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $info = self::http_request($url,json_encode($data),'json');

        $tmpinfo = json_decode($info);

        $code = $tmpinfo->errcode;
        if ($code != 0) {
            return errorJson('获取微信小程序信息错误');
        }

        $phone_info = $tmpinfo->phone_info;
        $phoneNumber = $phone_info->phoneNumber;
        if($code == '0'){
            return successJson('获取成功', ['phone'=>$phoneNumber]);
        }else{
            return errorJson('获取失败');
        }

    }

    /**
     * 商家登录
     */
    public function codeGetInfo(Request $request)
    {
        $all = $request->all();
        $all['login_method'] = 'WeChat';
        $all['login_type'] = 'small';
        $mobile = isset($all['mobile']) ? $all['mobile'] : '';
        //其他只能获取code再获取openid
        if (!$all['code']){
            return errorJson('code不能为空');
        }

//        $res = event(new \App\common\Events\ThirdPartyLogin($request, __E('wx_store_small_login_driver'), $all['login_method'], 'codeGetInfo', $all['login_type'], ['code' => $all['code']],'store'));
//        $wx = $res[0];
//        if (array_key_exists('errcode', $wx)) {
//            return errorJson('获取微信小程序信息错误');
//        }

        $wx['openid'] = 'ou-sd5TD61s6aG2vAVTZqthWif0I';
        $wx['session_key'] = 'hpJ7I7hnQxGRq61na/p2ng==';

        if (!$wx['openid']){
            return errorJson($wx['errmsg']);
        }

        //查询商户是否存在
        $all['login_type'] = 'wx_store_small';
        if ($wx['openid']) {
            $check = ThreeLogin::query()->where(['type'=>'store',"wx_small_openid"=>$wx['openid']])->first();
        } else {
            return errorJson('获取登录信息错误');
        }

        if ($check) {
            $uid = $check['uid'];
        } else {
            $salt = random(8);
            //注册
            $add['mobile'] = $mobile;
            $add['password'] = MD5('123456' . $salt);
            $add['salt'] = random(8);
            $add['createtime'] = time();
            $add['realname'] = substr($mobile, -4);
            $add['nickname'] = substr($mobile, -4);
            $add['type'] = 'store';
            $add['avatar'] = 'images/logo.png';
            $add['status'] = 1;
            $add['created_at'] = time();

            $uid = Members::insertGetId($add);

            //加第三方登录记录
            $addLogin = ThreeLogin::add([
                'uid' => $uid,
                'type' => 'store',
                'wx_unionid' => $wx['unionid'],
                'wx_small_openid' => $wx['openid']
            ]);

            if ($addLogin) {
                DB::commit();
            } else {
                DB::rollBack();
                return errorJson('注册失败');
            }
        }

        $data_info = Members::query()->where(['type'=>'store','uid'=>$uid])->select('uid', 'status', 'avatar', 'mobile', 'nickname')->first();
        if ($data_info['status'] != 1) {
            DB::rollBack();
            return errorJson('账号已禁用');
        }
        $data_info['ip'] = $request->getClientIp();
        $data_info = self::dealUserInfo($data_info);

        unset($data_info['ip']);
        return successJson($check ? "登录成功" : "注册成功", $data_info);


    }

    /**
     * 处理用户返回数据
     */
    public function dealUserInfo($data_info)
    {

        $token = auth('store')->login($data_info);
        $data_info->token = 'Bearer '.$token;
        //登录记录
        MembersLoginLogs::insert([
            'uid' => $data_info->uid,
            'ip' => $data_info->ip,
            'type' => 'store',
            'login_at' => getDay(),
            "device_type" => get_os(),
            "device_name" => get_broswer(),
            "device_token" => md5(uniqid())
        ]);
        return $data_info;
    }

    /**
     * 获取accessToken
     */
    public function getAccessToken()
    {
        $config = json_decode(file_get_contents(base_path() . '/app/common/Plugins/ThirdPartyLogin/config_store.json'), true);
        $appId = $config['wx_SMALL_APPID'];
        $appSecret = $config['wx_SMALL_APPSECRET'];

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appId . "&secret=" . $appSecret . "";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
        exit();

    }


}

